package com.zhijian.medical.util;

import cn.hutool.core.codec.Base64;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.converter.ExcelToHtmlUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.UUID;

/**
 * DOC格式Word预览工具类
 *
 * @author HCG
 * @version 1.0
 * @date 2022-11-24
 */
public class DocPreviewUtil {
    //32K
    private static final int BUFFER_SIZE = 2 << 15;

    /**
     * 输出html文件
     *
     * @param htmlFileName
     * @param resp
     * @throws IOException
     */
    public static void outputHtml(String htmlFileName, HttpServletResponse resp) throws IOException {
        resp.setHeader("Content-Type", "text/html; charset=UTF-8");
        File file = new File(htmlFileName);
        if (!file.exists()) throw new RuntimeException("此文件已被删除");
        //输出
        DataOutputStream dos = new DataOutputStream(resp.getOutputStream());
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        while ((len = bis.read(buffer)) > 0) {
            dos.write(buffer, 0, len);
        }
        try {
            bis.close();
            dos.close();
        } catch (Exception ex) {
        }
    }

    /**
     * 将word文档转换成为html文件
     *
     * @author www
     * @date 2014-8-20 8:53:58
     */
    public static String convertDoc2Html(String fileStoreName) throws Exception {
        File file = new File(fileStoreName);
        HWPFDocumentCore wordDocument = WordToHtmlUtils.loadDoc(file);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .newDocument());
        wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> String.format("data:%s;base64,%s", pictureType.getMime(), Base64.encode(content)));
        wordToHtmlConverter.processDocument(wordDocument);

        Document htmlDocument = wordToHtmlConverter.getDocument();

        Element body = (Element) htmlDocument.getElementsByTagName("body").item(0);
        body.setAttribute("style", "min-width:600px;");

        Element head = (Element) htmlDocument.getElementsByTagName("head").item(0);
        Element style = head.getOwnerDocument().createElement("style");
        style.setAttribute("type", "text/css");
        style.setTextContent(String.format("@media (max-width: 767px){body{margin:0 !important;padding:10px !important;}}"));
        head.appendChild(style);

        String uuid = UUID.randomUUID().toString();
        OutputStream out = new FileOutputStream(new File(uuid));
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();

        return uuid;
    }

    /**
     * 转换Excel为Html文档
     *
     * @param fileStoreName 存储文件名称
     * @param is2007        true表示是07格式的 即扩展名为.xlsx的 否则为03格式的
     * @return
     * @author www
     */
    public static String convertExcel2Html(String fileStoreName, boolean is2007) throws Exception {
        File file = new File(fileStoreName);
        HSSFWorkbook book;
        if (is2007) {//IF 2007, CONVERT IT TO 2003  : )   XLS -> XLSX
            book = new HSSFWorkbook();
            XSSFWorkbook book2 = new XSSFWorkbook(new FileInputStream(file));
            Xlsx2Xls x2x = new Xlsx2Xls();
            x2x.transformXSSF(book2, book);
        } else {
            book = ExcelToHtmlUtils.loadXls(file);
        }
        ExcelToHtmlConverter converter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        converter.processWorkbook(book);
        Document htmlDocument = converter.getDocument();
        String uuid = UUID.randomUUID().toString();
        OutputStream out = new FileOutputStream(new File(uuid));
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();

        return uuid;
    }
}
